<template>
  <div class="hello">
    <el-input v-model.trim="account.signatureKeyword"
              @change="checkKeyword(account.signatureKeyword, indexs, index)"
              :disabled="editFlag && editStatus"></el-input>
              <el-button @click="checkKeyword(account.signatureKeyword, indexs, index)">确定</el-button>
    <h1>{{ msg }}</h1>
    <div style="display: flex">
      <iframe id="myIframe" :src="url"
              frameborder="0"
              style="width: 100%; height: 440px"
      ></iframe>
      <div id="k" style="width: 300px"  @contextmenu.prevent.stop="openMenu($event)">{{selectText}}</div>
    </div>
  </div>
  <div class="defenseScreen" @contextmenu.prevent="openMenu($event)">
    <div class="mainBox"></div>
    <!-- 右击弹框设置 -->
    <ul v-show="visible" :style="{ left: menu.left + 'px', top: menu.top + 'px' }" class="contextmenu">
      <li @click="onc1()">引用</li>
      <li @click="onc1()">注释</li>
      <li @click="onc1()">翻译</li>
      <li @click="onc1()">复制</li>
    </ul>
  </div>

</template>

<script>
/* eslint-disable no-debugger */

// import * as PdfJs from 'pdfjs-dist/legacy/build/pdf.js' // 注意导入的写法
// import Pdf from '/pdf/js.pdf'
import { exceImportAPI } from '@/service/pageAjax'

export default {
  name: 'HelloWorld',
  data () {
    return {
      pdfPages: 0,
      url: '',
      selectText: '',
      visible: false, // 控制菜单栏的隐藏与展示
      menu: {
        top: 0, // 定义菜单栏出现的位置
        left: 0 // 定义菜单栏出现的位置
      },
      pdfDoc: null,
      account: { signatureKeyword: '' },
      pdfParams: {
        pageNumber: 1, // 当前页
        total: 0, // 总页数
        scale: 1, // 缩放
        rotate: 0 // 旋转角度
      }
    }
  },
  props: {
    msg: String
  },
  methods: {
    // 鼠标右击
    openMenu (e, left, top) {
      console.log(left, top, 'zou biao ')
      if (!left || !top) {
        // this.closeMenu()
        return
      }
      // 设置菜单栏出现的位置
      // const x = e.clientX
      // const y = e.clientY
      this.menu.top = top
      this.menu.left = left
      // 右击打开了菜单栏
      this.visible = true
    },
    // 菜单栏关闭执行回调
    closeMenu () {
      console.log('进关闭')
      this.visible = false
    },
    // 注册菜单
    onContextmenu (event) {
      event.preventDefault()
      this.$contextmenu({
        items: [
          {
            icon: 'el-icon-circle-plus-outline',
            label: '添加标签',
            onClick: () => {
              this.addTagVisible = true
            }
          }
        ],
        event,
        // 菜单显示X坐标, 存在event则失效
        // x: event.clientX,  //x轴坐标
        // y: event.clientY, //y轴坐标
        customClass: 'class-a',
        zIndex: 3,
        minWidth: 100
      })
      return false
    },

    onc1 () {
      console.log(111)
    },
    checkKeyword (val, indexs, index) {
      if (val.trim()) {
        const obj = {
          value: val,
          index: indexs,
          supIndex: index
        }
        this.sendMessage(obj)
      }
    },
    sendMessage (msg) {
      console.log(11)
      // document.getElementById('myIframe').contentWindow.postMessage(msg, '*')
      const iframe = document.getElementById('myIframe')
      iframe.contentWindow.postMessage(msg.value, '*')
      iframe.contentWindow.PDFViewerApplication.toolbar = false
      iframe.contentWindow.addEventListener('message', (e) => {
        console.log(e)
        console.log(iframe.contentWindow)
        iframe.contentWindow.PDFViewerApplication.findBar.findField.value = e.data
        iframe.contentWindow.PDFViewerApplication.findBar.highlightAll.checked = false
        console.log(iframe.contentWindow.PDFViewerApplication.findBar)
        iframe.contentWindow.PDFViewerApplication.findBar.dispatchEvent('highlightallchange')
      }, false)
      console.log(iframe.contentWindow.PDFViewerApplication.pagesCount)
      // iframe.contentWindow.PDFViewerApplication.pagesCount
    },
    bindEvent (element, eventName, eventHandler) {
      if (element.addEventListener) {
        //  addEventListener support for IE8
        element.addEventListener(eventName, eventHandler, false)
      } else if (element.attachEvent) {
        element.attachEvent('on' + eventName, eventHandler)
      }
    },
    aa (url) {
      // PdfJs.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry')
      // const loadingTask = PdfJs.getDocument(url)
      // loadingTask.promise.then((pdf) => {
      //   this.pdfDoc = pdf // 保存加载的pdf文件流
      //   this.pdfPages = this.pdfDoc.numPages // 获取pdf文件的总页数
      //   this.$nextTick(() => {
      //     this.renderPage(1) // 将pdf文件内容渲染到canvas，
      //   })
      // })
    },
    f () {
      const vm = this

      const iframe = document.getElementById('myIframe')
      console.log(iframe.scrollWidth, iframe.scrollHeight, iframe.offsetTop, iframe.offsetLeft)
      let x = ''
      let y = ''
      let _x = ''
      let _y = ''// iframe 加载完成后执行并将双击事件过滤掉，因为双击事件可能也触发滑选，所以为了不误操作，将其剔除
      iframe.onload = function () { // 鼠标点击监听
        iframe.contentWindow.document.oncontextmenu = function (e) { vm.openMenu(e); return false }

        iframe.contentDocument.addEventListener('mousedown', function (e) {
          x = e.pageX; y = e.pageY
          console.log(x, y, _x, _y)
        }, true)

        // 鼠标抬起监听
        iframe.contentDocument.addEventListener('mouseup', function (e) {
          console.log(x, y, _x, _y)
          _x = e.pageX; _y = e.pageY
          if (x === _x && y === _y) {
            vm.closeMenu()
            return
          }
          // 判断点击和抬起的位置，如果相同，则视为没有滑选，不支持双击选中
          // console.log(iframe.contentWindow.getSelection())
          console.log(iframe.contentWindow)
          // console.log(iframe.contentWindow.getComputedStyle)
          // console.log(iframe.contentWindow.getActualStyle())
          var choose = iframe.contentWindow.getSelection().toString(); console.log(choose); vm.selectText = choose
          //
          // if (!document.getElementById('map')) {
          //   const aa = document.createElement('div')
          //   aa.id = 'map'
          //   document.body.appendChild(aa)
          // }
          // const map = document.getElementById('map')
          // map.style.position = 'absolute'
          // map.style.width = 80 + 'px'
          // map.style.height = 80 + 'px'
          // map.style.background = '#ff4f02'
          // map.style.border = '1px solid #ccc'
          // map.style.left = x + 'px'
          // map.style.top = y + iframe.offsetTop + 'px'
          // console.log(3213)

          iframe.contentWindow.postMessage('数组', '*')

          if (vm.selectText) {
            vm.openMenu(e, x, y + iframe.offsetTop + 30)
          } else {
            vm.closeMenu()
          }
        }, true)
        // 自定义鼠标右键事件
        // iframe.contentWindow.oncontextmenu = function (event) {
        //   if (vm.selectText) {
        //     // 重新设置菜单位置，如果菜单位置正常可忽略
        //     Object.defineProperty(event, 'clientX', {
        //       value: event.screenX,
        //       writable: true,
        //       configurable: true,
        //       enumerable: true
        //     })
        //     // 重新设置菜单位置，如果菜单位置正常可忽略
        //     Object.defineProperty(event, 'clientY', {
        //       value: event.screenY - 100,
        //       writable: true,
        //       configurable: true,
        //       enumerable: true
        //     })
        //     // alert('请不要点击鼠标右键！');
        //     vm.onContextmenu(event)
        //     return false// 组织浏览器右键
        //   }
        // }
        iframe.contentWindow.onclick = function () {
          // vm.closeMenu()
          // vm.contextmenuDestory()
        }
      }
    }
  },
  mounted () {
    // this.aa(Pdf)
    // const fileUrl = 'xxx'
    // this.url = '/pdf/web/viewer.html?file=/pdf/js.pdf'

    const params = {
      filename: 'https://commoncms.ynyplt.cn/file-server/2023/06/3d958bf1-bce9-4688-977e-f4bff27ff432.pdf'
    }

    exceImportAPI(params).then(res => {
      const blob = new Blob([res], { type: '"text/xlsx,;charset=utf-8;' })

      const url = window.URL || window.webkitURL
      // 将blob对象创建新的url
      const blobUrl = url.createObjectURL(blob)
      // 将url传送到PDF.js
      this.url = '/pdf/web/viewer.html?file=' + blobUrl
    })

    const checkPdf = () => {
      const pdfFrame = document.getElementById('myIframe').contentWindow
      pdfFrame.PDFViewerApplication.page = 3
      // this.currentPage.value = pdfFrame.PDFViewerApplication.page
      console.log(pdfFrame.PDFViewerApplication)
    }

    // 获取当前第几页，而可以根据当前页
    // pdfFrame.PDFViewerApplication.page

    setTimeout(() => { checkPdf() }, 5000)

    const vm = this
    vm.f()
    // const c = encodeURIComponent('https://commoncms.ynyplt.cn/file-server/13648711629/9b613676-d867-47e3-873d-47d6d59015d5.pdf#page=1')
    // this.url = '/pdf/web/viewer.html?file=' + c
    // window.open('/pdf/web/viewer.html?file=/pdf/js.pdf')
  }
  // async mounted () {
  //   const pdfjs = await import('pdfjs-dist/build/pdf.js')
  //   const pdfjsWorker = await import('pdfjs-dist/build/pdf.worker.entry')
  //   pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker
  //   // 加载pdf文件，本地文件会有跨域问题，下面这个地址是不对的，自行更换
  //   const url = '/pdf/web/viewer.html?file=/pdf/js.pdf'
  //
  //   pdfjs.getDocument(url)
  //     .promise.then(doc => {
  //       this.pdfDoc = doc
  //       console.log('内容：', doc, doc.numPages)
  //       this.pdfParams.total = doc.numPages
  //       // getPdfPage(1)
  //     })
  // }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

<style scoped>
  .defenseScreen {
    height: 100vh;
    background-size: 100% 100%;
  }
  .contextmenu {
    margin: 0;
    background:#fff;
    z-index: 3000;
    position: fixed;
    list-style-type: none;
    padding: 5px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 400;
    color: #333;
    box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
  }

  .contextmenu li {
    margin: 0;
    padding: 7px 16px;
    cursor: pointer;
  /*// 定义一下动画*/
  transition:all .3s;
  }
  /*// 移动上去有底色分辨*/
     .contextmenu li:hover {
       background-color: rgb(57, 143, 114);
       color: white;
     }
</style>
